<template>
    <div class="city-header">
        <div class="title"><i class="iconfont icon-fanhui flt" @click="back"></i>城市选择</div>
        <div class="search"><input type="text" placeholder="输入城市或拼音" v-model.trim="ipt"></div>

        <div class="search-result" v-show="ipt">
            <p v-for="item in searchResult">{{ item.name }}</p>
        </div>
    </div>
</template>

<script>
    export default {
        name: "CityHeader",
        props: ['cities'],
        data() {
            return {
                ipt: '',
                searchResult: []
            }
        },
        watch: {
            ipt() { // 监听文本框内容的改变
                // 清空之前的搜索结果
                this.searchResult = []
                // 遍历cities中的键
                Object.keys(this.cities).forEach((key) => {
                    // 根据键对应的数组过滤包含文本框内容的城市
                    var ary = this.cities[key].filter((item) => {
                        return item.spell.indexOf(this.ipt) > -1
                    })
                    // 把过滤结果合并之后重新赋值给全局变量
                    this.searchResult = this.searchResult.concat(ary)
                })
            }
        },
        methods: {
            back() {
                this.$router.go(-1)
                // this.$router.push('/')
            }
        }
    }
</script>

<style scoped>
    .city-header {
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        background: rgb(0,188,212);
    }
    .title {
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-bottom: 1px solid #eeeeee;
        font-size: 14px;
        color: white;
        padding: 0 10px;
        box-sizing: border-box;
    }
    .title i {
        font-size: 22px;
    }
    .search {
        padding: 5px 10px;
        box-sizing: border-box;
    }
    input {
        width: 100%;
        height: 25px;
        line-height: 25px;
        border: none;
        background: white;
        border-radius: 3px;
        text-align: center;
        outline: none;
    }

    .search-result {
        position: absolute;
        left: 0;
        width: 100%;
        height: 300px;
        background: white;
        /*内容超出高度自动添加滚动条*/
        overflow: auto;
        border: 1px solid #eeeeee;
        box-sizing: border-box;
    }

    .search-result p {
        padding: 0 10px;
        height: 25px;
        line-height: 25px;
        box-sizing: border-box;
        font-size: 14px;
    }
    .search-result p:hover {
        background: #eeeeee;
    }

</style>